import type { RequestOptions } from '@/types/uni-app'

const BASE_URL = process.env.VUE_APP_API_BASE || 'https://api.example.com'
const MAX_RETRY = 2
const TIMEOUT = 10000

interface ApiResponse<T> {
  code: number
  data: T
  message: string
  timestamp?: number
}

interface UserInfo {
  id: number
  name: string
  avatar: string
  email?: string
  phone?: string
  roles?: string[]
}

interface RequestConfig extends RequestOptions {
  retry?: number
  timeout?: number
  headers?: Record<string, string>
}

// 请求队列
const pendingRequests: Record<string, UniApp.RequestTask> = {}

// 请求拦截器
const requestInterceptor = (config: RequestConfig): RequestConfig => {
  // 添加认证token
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = config.header || {}
    config.header['Authorization'] = `Bearer ${token}`
  }

  // 设置超时
  config.timeout = config.timeout || TIMEOUT

  return config
}

// 响应拦截器
const responseInterceptor = <T>(response: UniApp.RequestSuccessCallbackResult): ApiResponse<T> => {
  if (response.statusCode !== 200) {
    throw new Error(`请求失败，状态码: ${response.statusCode}`)
  }

  const data = response.data as ApiResponse<T>
  if (data.code !== 200) {
    throw new Error(data.message || '请求处理失败')
  }

  return data
}

// 基础请求方法
const request = <T>(config: RequestConfig): Promise<T> => {
  return new Promise((resolve, reject) => {
    config = requestInterceptor(config)
    let retryCount = 0

    const doRequest = (): void => {
      const task = uni.request({
        ...config,
        success: (res) => {
          try {
            const data = responseInterceptor<T>(res)
            resolve(data.data)
          } catch (error) {
            if (retryCount < (config.retry || MAX_RETRY)) {
              retryCount++
              setTimeout(doRequest, 1000 * retryCount)
            } else {
              reject(error)
            }
          }
        },
        fail: (err) => {
          if (retryCount < (config.retry || MAX_RETRY)) {
            retryCount++
            setTimeout(doRequest, 1000 * retryCount)
          } else {
            reject(err)
          }
        },
        complete: () => {
          delete pendingRequests[config.url!]
        }
      } as RequestOptions)

      pendingRequests[config.url!] = task
    }

    doRequest()
  })
}

// 取消请求
export const cancelRequest = (url: string) => {
  if (pendingRequests[url]) {
    pendingRequests[url].abort()
    delete pendingRequests[url]
  }
}

// 取消所有请求
export const cancelAllRequests = () => {
  Object.values(pendingRequests).forEach(task => task.abort())
  Object.keys(pendingRequests).forEach(key => delete pendingRequests[key])
}

// 用户API
export const userApi = {
  fetchUserInfo(userId: number): Promise<UserInfo> {
    return request<UserInfo>({
      url: `${BASE_URL}/user/${userId}`,
      method: 'GET'
    })
  },

  login(username: string, password: string): Promise<UserInfo> {
    return request<UserInfo>({
      url: `${BASE_URL}/auth/login`,
      method: 'POST',
      data: { username, password },
      retry: 1
    })
  },

  logout(): Promise<void> {
    return request<void>({
      url: `${BASE_URL}/auth/logout`,
      method: 'POST'
    })
  },

  updateProfile(userId: number, data: Partial<UserInfo>): Promise<UserInfo> {
    return request<UserInfo>({
      url: `${BASE_URL}/user/${userId}`,
      method: 'PUT',
      data
    })
  }
}